<template>
	<view class="mbti-device">
		<mBack ref="mBack" @getGameResult="handleBack"></mBack>
		<view class="mbti-device-content flex-column-start-center" :style="{'background-image': `url(${bgUrl})`}">
			<view class="top-box" :style="{height:contentTop+'rpx'}"></view>
			<view class="content-box flex-column-start-center" v-if="deviceData">
				<view class="device-avatar" @click="closeBluetooth">
					<image class="cover-img" :src="deviceData.avatar" mode="aspectFill"></image>
				</view>
				<view class="device-nick-info flex-row-center-center">
					<view class="device-nick-name">{{deviceData.nickName}}</view>
					<view class="device-nick-sex">
						<image class="cover-img"
							src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/2b43d0df19bb46978d14461dc9254bde.png"
							mode="aspectFill" v-if="deviceData.agentSex=='0'"></image>
						<image class="cover-img"
							src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/2f5cb5a5c1bf4cdc9a7fdf2173793dda.png"
							mode="aspectFill" v-else></image>
					</view>
					<view class="device-nick-label">
						<image class="cover-img" :src="deviceData.label" mode="aspectFill"></image>
					</view>
				</view>
				<view class="device-name-info flex-row-center-center" @click="handleOpenEdit">
					<view class="device-name"><text style="font-weight: 500;">{{deviceData.alias}}</text>的Clackey</view>
					<view class="device-name-edit flex-row-center-center">
						<image class="device-name-edit-icon"
							src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/687f0d08cb1c4c4d8f41de5b2c07a360.png"
							mode="aspectFill"></image>
					</view>
				</view>
				<view class="device-sn-info flex-row-center-center">SN：{{deviceData.id}}</view>
				<view class="device-link-info flex-column-start-center">
					<view class="no-link flex-column-start-center" v-if="!deviceData.onlineStatus">
						<view class="link-icon" @click="handleTestDeviceConnect">
							<image class="cover-img"
								src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/c9556c6c4a8a4b2ba7ebf4cea250392a.png"
								mode="aspectFill"></image>

						</view>
						<view class="to-link-button flex-row-center-center" @click="handleToLinkInternet">连接网络</view>
					</view>

					<view class="is-link flex-column-start-center" v-else>
						<view class="link-icon">
							<image class="cover-img"
								src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/2316b82b988d43458b2c42ab3eedccba.png"
								mode="widthFix"></image>
						</view>
						<view class="wifi-name flex-row-center-center">
							已连接：{{deviceData.wifiName}}
						</view>
						<view class="lead-to-other flex-row-center-center" @click="handleToLinkInternet">
							连接其他网络
						</view>

					</view>
				</view>
				<!-- 924 -->
				<view class="device-bottom-bg">
					<image class="cover-img" :src="deviceData.bottomBg" mode="aspectFill"></image>
				</view>

			</view>
		</view>


		<mbtiPop ref="mbtiPop" @confirmValue="handlePopConfirm" @cancel="handlePopCancel" @callBack="handlePopCallBack">
		</mbtiPop>
	</view>
</template>

<script>
	import mBack from "@/components/m-back/index.vue"
	import mbtiPop from "@/components/m-mbti/mbti-pop.vue"

	import BluFiController from '@/utils/blufi-core.js';
	import {
		getNowDeviceInfo,
		deviceUpdate,
		getUserDevice
	} from "@/api/mbti.js"
	import {
		getMbtiSourceByKey
	} from "@/utils/mbti-source"
	export default {
		components: {
			mBack,
			mbtiPop
		},
		data() {
			return {
				bgUrl: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/d394a848c52a40a0b7fc9baf22ba6a01.png",
				screenWidth: 375,
				rpxMenuButtonHeight: 64,
				rpxMenuButtonTop: 100,
				contentTop: 300,
				id: null,
				deviceData: null,
				form: null,
				formArr: [{
						type: "label-none",
						subLabel: "Agent对我的称呼",
						label: "的Clackey",
						value: "",
						limit: -1,
						code: "alias",
						valueType: "text",
						isRequire: true
					},
					{
						type: "line"
					},
					{
						type: "label-none",
						subLabel: "Agent昵称",
						label: "",
						value: "",
						limit: -1,
						code: "agentNickname",
						valueType: "text"
					},
					{
						type: "label-none",
						subLabel: "Agent音色",
						label: "",
						value: "",
						limit: -1,
						code: "agentSex",
						valueType: "sex"
					},
				],

				// 蓝牙测试
				bluetoothState: false, // 蓝牙适配器状态
				scanning: false, // 扫描状态
				devices: [], // 发现设备列表
				connectedDevice: null, // 已连接设备
				serviceId: '', // 动态获取的服务ID
				characteristicId: '', // 动态获取的特征值ID
				notifyChar: "", //读特征ID
				writeChar: "", //写特征ID
				deviceCache: new Map(), // 设备信息缓存


				// 我的数据
				deviceIsConnected: false,
				mockDevice: {
					serviceId: "0000FFFF-0000-1000-8000-00805F9B34FB", //服务uuid
					notifyChar: "0000FF02-0000-1000-8000-00805F9B34FB", //接收通知uuid
					writeChar: "0000FF01-0000-1000-8000-00805F9B34FB", //写uuid
					deviceId: "F0:9E:9E:04:8A:36", //设备id   D9CDE327-42BA-D375-AF04-E86BBE4A1893 ios

				}
			}
		},
		created() {
			try {
				let screenWidth = uni.getStorageSync('screenWidth')
				if (screenWidth) {
					this.screenWidth = screenWidth
				} else {
					this.screenWidth = uni.getSystemInfoSync().screenWidth; // 当前设备屏幕宽度
					uni.setStorageSync("screenWidth", this.screenWidth)
				}
				let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
				let {
					top,
					height
				} = menuButtonInfo

				let rpxHeight = this.pxToRpx(height)
				let rpxTop = this.pxToRpx(top)
				this.rpxMenuButtonHeight = rpxHeight
				this.rpxMenuButtonTop = rpxTop
				this.contentTop = rpxTop + rpxHeight + 128

			} catch (error) {
				//TODO handle the exception
			}
		},
		onLoad(e) {
			// this.id = e.id
			// console.log("传递过来的设备id", this.id);
			this.handleGetUserDevice()
			this.handleGetNowDeviceInfo()

		},
		onShow() {
			this.handleGetNowDeviceInfo()
		},
		watch: {
			form: {
				handler(newVal, oldVal) {
					if (newVal) {
						Object.entries(newVal).forEach((item, index) => {
							this.handleUpdateFormDataList(item[0], item[1])
						})
						console.log("新的数组", this.formArr);
					}
				},
				deep: true
			}
		},
		methods: {
			pxToRpx(px) {
				const designWidth = 750; // 设计稿宽度
				const rpx = (designWidth / this.screenWidth) * px; // 根据屏幕宽度计算 rpx
				return rpx;
			},
			handleBack() {
				uni.navigateBack()
			},
			async handleGetUserDevice() {
				let res = await getUserDevice()
				let list = null
				try {
					list = res.data.data
				} catch {

				}
				if (!list) {
					return
				}
				// this.userDeviceList = [...list]
				console.log("用户设备数据是", list)
				if (!list.length) {
					uni.navigateBack()
				}

			},
			handleUpdateFormDataList(code, value) {
				this.formArr.forEach((item, index) => {
					if (item.code == code) {
						item.value = value
					}
				})
			},
			// 蓝牙部分
			handleTestDeviceConnect() {
				// this.devices.find((item, index) => {
				// 	if (String(item.name).includes("MBTI_DEVICE")) {
				// 		this.connectDevice(item)
				// 	}
				// })

				this.handleConnectDevice() // 蓝牙
			},
			// 我的初始化蓝牙
			handleBluFiInit() {
				return new Promise((resolve, reject) => {
					uni.openBluetoothAdapter({
						success: (res) => {
							this.bluetoothState = true
							resolve(true)
						},
						fail: (err) => {
							uni.showToast({
								title: "请开启手机蓝牙",
								icon: "none"
							})
							reject(false)
						}
					})
				})
			},
			// 初始化蓝牙
			initBluetooth() {
				try {
					uni.openBluetoothAdapter({
						success: (res) => {
							this.bluetoothState = true
							console.log("初始化完毕");
							this.listenBluetoothState()
							this.startScan() //扫描不是在这里做的 是在绑定设备的时候做的
						},
						fail: (err) => {
							uni.showToast({
								title: "请开启手机蓝牙",
								icon: "none"
							})
							console.error('初始化失败:', err)
							// this.handleBluetoothError(err)
						}
					})
				} catch (err) {
					this.statusText = '请打开手机蓝牙功能'
					console.error('初始化失败:', err)
				}
			},
			// 监听蓝牙适配器状态变化[4](@ref)
			listenBluetoothState() {
				uni.onBluetoothAdapterStateChange(res => {
					console.log('适配器状态变化:', res)
					this.bluetoothState = res.available
					if (!res.available) this.clearAllStates()
				})
			},
			// 开始扫描设备[3,7](@ref)
			startScan() {
				if (!this.bluetoothState) return
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: false,
					interval: 2000,
					success: (res) => {
						console.log('开始扫描', res)
						this.scanning = true
						this.setupDeviceListener()
						setTimeout(() => this.stopScan(), 120000) // 120秒后自动停止
					},
					fail: this.handleScanError
				})
			},
			// 设置设备发现监听[7](@ref)
			setupDeviceListener() {
				uni.onBluetoothDeviceFound(devices => {
					devices.devices.forEach(device => {
						if (!this.deviceCache.has(device.deviceId) && device.name) {
							this.deviceCache.set(device.deviceId, device)
							this.devices = Array.from(this.deviceCache.values())
						}
					})
					console.log('当前设备', this.devices)
				})
			},

			// 停止扫描[7](@ref)
			stopScan() {
				uni.stopBluetoothDevicesDiscovery({
					complete: () => {
						this.scanning = false
						console.log('已停止扫描', this.devices)
					}
				})
			},
			// 连接设备[3,5](@ref)
			async connectDevice(device) {
				try {
					await this.createConnection(device.deviceId)
					const services = await this.getDeviceServices(device.deviceId)
					this.serviceId = services.find(s => s.isPrimary).uuid
					const characteristics = await this.getCharacteristics(device.deviceId)
					console.log("最终连接服务id", this.serviceId);
					console.log("最终连接特征值", characteristics);

					this.connectedDevice = device
					this.setupCharacteristic(characteristics)
					this.listenDisconnection()
				} catch (error) {
					console.error('连接失败:', error)
				}
			},
			// 创建BLE连接[4](@ref)
			createConnection(deviceId) {
				return new Promise((resolve, reject) => {
					uni.createBLEConnection({
						deviceId,
						success: resolve,
						fail: reject
					})
				})
			},

			// 获取设备服务[4](@ref)
			getDeviceServices(deviceId) {
				return new Promise((resolve, reject) => {
					uni.getBLEDeviceServices({
						deviceId,
						success: res => resolve(res.services),
						fail: reject
					})
				})
			},

			// 获取特征值[4](@ref)
			getCharacteristics(deviceId) {
				return new Promise((resolve, reject) => {
					uni.getBLEDeviceCharacteristics({
						deviceId,
						serviceId: this.serviceId,
						success: res => resolve(res.characteristics),
						fail: reject
					})
				})
			},
			// 自己的
			// 连接设备
			async handleConnectDevice() {

				// 初始化蓝牙模块
				await this.handleBluFiInit()
				// 开启设备扫描
				await this.handleStartDeviceDiscovery()
				// 监听设备扫描
				await this.handleListenDiveceSearch(60000)
				// 扫到之后连接
				await this.handleCreateDeviceConnect()
				// 连接后监听硬件蓝牙通知 - 读取
				await this.handleListenNotify()


				// this.createConnection(this.mockDevice.deviceId).then(res => {
				// 	console.log("连接成功", res);
				// 	this.enableNotify()
				// }).catch(err => {
				// 	console.log("连接失败", err);
				// })

			},



			// 开启设备扫描
			handleStartDeviceDiscovery() {
				return new Promise((resolve, reject) => {
					uni.startBluetoothDevicesDiscovery({
						allowDuplicatesKey: false,
						interval: 1000,
						success: (res) => {
							resolve(true)
						},
						fail: err => {
							uni.showToast({
								title: "设备扫描开启失败",
								icon: "none"
							})
						}
					})
				})

			},
			// 监听设备扫描
			handleListenDiveceSearch(time = 20000) {
				console.log("设备扫描中...");
				return new Promise((resolve, reject) => {
					uni.onBluetoothDeviceFound(devices => {
						devices.devices.forEach(device => {
							if (device.deviceId == this.mockDevice.deviceId) {
								console.log('扫描到设备了', device.name);
								resolve(true)
							}
						})
					})
					setTimeout(() => {
						reject(false)
						uni.showToast({
							title: "未找到设备",
							icon: "none"
						})
					}, time)
				})
			},
			// 设备连接
			handleCreateDeviceConnect() {
				return new Promise((resolve, reject) => {
					uni.createBLEConnection({
						deviceId: this.mockDevice.deviceId,
						success: res => {
							console.log("设备连接成功...");
							this.deviceIsConnected = true
							resolve(true)
						},
						fail: err => {
							uni.showToast({
								title: "设备连接失败",
								icon: "none"
							})
						}
					})
				})
			},

			// 启用通知 	读取
			handleListenNotify() {
				uni.notifyBLECharacteristicValueChange({
					deviceId: this.mockDevice.deviceId,
					serviceId: this.mockDevice.serviceId,
					characteristicId: this.mockDevice.notifyChar,
					state: true,
					success: () => {
						console.log("开启通知监听成功");
						uni.onBLECharacteristicValueChange(this.handleDataReceived);
					},
					fail: err => {
						console.log("开启通知失败", err);
					}
				});
			},
			// 写入数据
			// 发送BluFi配置数据
			async sendBlufiConfig(ssid, password) {
				if (!ssid || !password) return;

				const frame = this.buildBlufiFrame(ssid, password);
				const chunks = this.splitData(frame);
				console.log("分片成功", chunks);
				// return

				for (const chunk of chunks) {
					await this.writeData(chunk);
					await this.delay(50); // 添加发送间隔
				}
			},

			// 构建BluFi数据帧（简化版）
			buildBlufiFrame(ssid, password) {
				const ssidBuffer = this.strToBuffer(ssid);
				const pwdBuffer = this.strToBuffer(password);
				const frame = new Uint8Array([
					0x01, // 帧类型
					ssidBuffer.length,
					...ssidBuffer,
					pwdBuffer.length,
					...pwdBuffer
				]);
				return frame;
			},

			// 数据分片处理
			splitData(data, chunkSize = 20) {
				const chunks = [];
				for (let i = 0; i < data.length; i += chunkSize) {
					chunks.push(data.slice(i, i + chunkSize));
				}
				return chunks;
			},

			// 写入数据
			writeData(data) {
				return new Promise((resolve, reject) => {
					uni.writeBLECharacteristicValue({
						deviceId: this.mockDevice.deviceId,
						serviceId: this.mockDevice.serviceId,
						characteristicId: this.mockDevice.writeChar,
						value: data.buffer,
						success: res => {
							console.log("写入成功");
							resolve(true)
						},
						fail: err => {
							console.log("写入失败");
							reject(false)
						}
					});
				});
			},

			// 工具方法：字符串转ArrayBuffer
			strToBuffer(str) {
				const buffer = new Uint8Array(str.length);
				for (let i = 0; i < str.length; i++) {
					buffer[i] = str.charCodeAt(i);
				}
				return buffer;
			},

			// 工具方法：ArrayBuffer转十六进制
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					bit => ('00' + bit.toString(16)).slice(-2)
				);
				return hexArr.join('');
			},

			// 延时函数
			delay(ms) {
				return new Promise(resolve => setTimeout(resolve, ms));
			},



			// 

			// 设置特征值[3](@ref)
			setupCharacteristic(characteristics) {
				const writeChar = characteristics.find(c => c.properties.write)
				const notifyChar = characteristics.find(c => c.properties.notify)

				// 每次获取一次读、写特征id 先考虑联网
				console.log("宝宝writeChar", writeChar);
				console.log("宝宝notifyChar", notifyChar);
				return
				if (writeChar) this.writeChar = writeChar.uuid

				if (notifyChar) {
					this.notifyChar = notifyChar.uuid
					uni.notifyBLECharacteristicValueChange({
						deviceId: this.connectedDevice.deviceId,
						serviceId: this.serviceId,
						characteristicId: notifyChar.uuid,
						state: true
					})
					uni.onBLECharacteristicValueChange(this.handleDataReceived)
				}
			},

			// 数据接收处理[3](@ref)
			handleDataReceived(res) {
				const value = this.ab2hex(res.value)
				console.log('收到数据:', res, value)
				// 这里添加数据解析逻辑
			},

			// ArrayBuffer转Hex[3](@ref)
			// ab2hex(buffer) {
			// 	return Array.prototype.map.call(
			// 		new Uint8Array(buffer),
			// 		x => ('00' + x.toString(16)).slice(-2)
			// 	).join('')
			// },

			// 关闭蓝牙[4](@ref)
			closeBluetooth() {
				uni.closeBluetoothAdapter()
				this.clearAllStates()
			},

			// 错误处理统一方法[4](@ref)
			handleBluetoothError(err) {
				const errorMap = {
					10000: '未初始化蓝牙适配器',
					10001: '当前蓝牙适配器不可用',
					10002: '没有找到指定设备',
					10003: '连接失败或已断开连接'
				}
				uni.showToast({
					title: errorMap[err.errCode] || `蓝牙错误: ${err.errMsg}`,
					icon: 'none'
				})
			},

			// 监听断开连接[5](@ref)
			listenDisconnection() {
				uni.onBLEConnectionStateChange(res => {
					if (!res.connected) {
						this.clearConnection()
						uni.showToast({
							title: '设备已断开',
							icon: 'none'
						})
					}
				})
			},
			clearConnection() {

			},
			// 清空所有状态
			clearAllStates() {
				this.devices = []
				this.deviceCache.clear()
				this.connectedDevice = null
				this.serviceId = ''
				this.characteristicId = ''
			},

			// 
			async handleToLinkInternet() {
				// this.clearAllStates()
				// this.stopScan()
				// this.initBluetooth()


				// try {
				// 	let status = '正在初始化...';
				// 	const blufi = new BluFiController();
				// 	// blufi.deviceId = this.mockDevice.deviceId
				// 	console.log("示例是", blufi);

				// 	await blufi.init();

				// 	status = '发送凭证中...';
				// 	console.log(status);
				// 	await blufi.sendCredentials("XingZai", "xingzaitech.com");

				// 	status = '配网成功！等待设备连接';
				// 	console.log(status);
				// } catch (err) {
				// 	let status = `错误: ${err.message}`;
				// 	console.log(status);
				// }


				// return

				// 
				// if (!this.deviceIsConnected) {
				// 	uni.showToast({
				// 		title: "请先连接设备蓝牙",
				// 		icon: "none"
				// 	})
				// 	return
				// }

				// this.sendBlufiConfig("XingZai", "xingzaitech.com")


				// uni.navigateTo({
				// 	url: "/pages/mbti/mbti-wifi"
				// })
				// return
				wx.openBluetoothAdapter({
					success: (res) => {
						uni.navigateTo({
							url: "/pages/mbti/mbti-wifi"
						})
					},
					fail: (err) => {
						uni.showToast({
							title: "请先打开手机蓝牙",
							icon: "none"
						})
					}
				})

			},


			// 
			handleUpdateDevice() {
				deviceUpdate(this.form).then(res => {
					console.log("修改完毕", res);
					uni.showToast({
						title: "修改成功",
						icon: "none"
					})
					this.handleGetNowDeviceInfo()
				})
			},
			handlePopCallBack() {

			},
			handlePopCancel() {

			},
			handlePopConfirm(e) {
				let {
					data
				} = e

				let arr = [...data]
				arr.forEach((item, index) => {
					this.form[String(item.code)] = item.value
				})

				this.handleUpdateDevice()
			},
			handleOpenEdit() {
				this.$refs.mbtiPop.open({
					data: this.formArr,
					title: "Clackey设置"
				})
			},
			handleGetNowDeviceInfo() {
				getNowDeviceInfo().then(res => {
					let data = res.data.data
					// let code = res.data.code
					// if (code == '401') {
					// 	this.handleGetNowDeviceInfo()
					// 	return
					// }
					if (data) {

						let source = getMbtiSourceByKey(data.mbti)
						let bottomBg = ""
						let avatar = ""
						let nickName = data.agentNickname ? data.agentNickname : ""
						let label = ""
						if (source) {
							bottomBg = source.opacityBottomBg
							avatar = source.largeAvatar
							nickName = !nickName ? source.nickName : nickName
							label = source.label
						}

						this.form = {
							...data
						}
						this.form.agentNickname = nickName
						this.form.agentSex = !this.form.agentSex ? "0" : this.form.agentSex

						this.deviceData = {
							...data,
							bottomBg,
							avatar,
							nickName,
							label,
						}
						console.log("设备详情是", this.deviceData);

					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.mbti-device {
		position: absolute;
		left: 0rpx;
		top: 0rpx;
		width: 100%;
		height: 100%;
		background-color: #ededed;
		box-sizing: border-box;

		.mbti-device-content {
			width: 100%;
			height: 100%;
			background-repeat: no-repeat;
			background-size: cover;
			background-position: center center;
			padding: 0rpx 48rpx;

			.top-box {
				width: 100%;
			}

			.content-box {
				position: relative;
				width: 100%;
				flex: 1;

				.device-bottom-bg {
					position: absolute;
					left: 50%;
					top: 924rpx;
					transform: translateX(-50%);
					width: 100vw;
					height: 400rpx;

				}

				.device-avatar {
					width: 280rpx;
					height: 280rpx;
					margin-bottom: 74rpx;

				}

				.device-nick-info {
					width: 100%;
					height: 48rpx;
					margin-bottom: 24rpx;

					.device-nick-name {
						height: 44rpx;
						font-weight: 400;
						font-size: 32rpx;
						color: #6D7278;
						line-height: 44rpx;
						margin-right: 16rpx;
					}

					.device-nick-sex {
						width: 48rpx;
						height: 48rpx;
						margin-right: 16rpx;
					}

					.device-nick-label {
						width: 80rpx;
						height: 36rpx;
					}

				}

				.device-name-info {
					width: 100%;
					height: 56rpx;
					font-size: 40rpx;
					color: #153135;
					line-height: 56rpx;
					margin-bottom: 24rpx;

					.device-name {
						margin-right: 16rpx;
					}

					.device-name-edit {
						width: 48rpx;
						height: 48rpx;
						background: #F5F5F5;
						border-radius: 50%;

						.device-name-edit-icon {
							width: 24rpx;
							height: 24rpx;
						}
					}
				}

				.device-sn-info {
					width: 100%;
					height: 40rpx;
					font-weight: 300;
					font-size: 28rpx;
					color: #ADADAD;
					line-height: 40rpx;
					margin-bottom: 124rpx;
				}

				.device-link-info {
					width: 100%;

					.no-link {
						width: 100%;


					}

					.is-link {
						width: 100%;
					}

					.link-icon {
						width: 64rpx;
						height: 56rpx;
						margin-bottom: 48rpx;
					}

					.to-link-button {
						width: 454rpx;
						height: 96rpx;
						border-radius: 28rpx;
						border: 2rpx solid #99C26D;
						font-weight: 400;
						font-size: 32rpx;
						color: #153135;
						line-height: 44rpx;
					}

					.wifi-name {
						width: 100%;
						height: 40rpx;
						font-weight: 400;
						font-size: 28rpx;
						color: #ADADAD;
						line-height: 40rpx;
						margin-bottom: 40rpx;

					}

					.lead-to-other {
						width: 100%;
						height: 40rpx;
						font-weight: 400;
						font-size: 28rpx;
						color: #99C26D;
						line-height: 40rpx;
					}
				}
			}
		}

	}
</style>